package com.dg.river.core.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.dg.river.R;
import com.dg.river.core.util.FileUtils;
import com.dg.river.core.util.L;
import com.dg.river.core.util.TextUtil;
import com.dg.river.core.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;

import java.io.File;

import okhttp3.HttpUrl;

/**
 * Created by hy on 2018/10/16
 * Description : 升级弹窗
 */
public class UpgradeDialog extends Dialog {

    public UpgradeDialog(Context context) {
        super(context);
    }

    public UpgradeDialog(Context context, int theme) {
        super(context, theme);
    }

    public static class Builder {
        private Context mContext;
        private boolean cancel;
        private String versionName;
        private int versionCode;
        private String upgradeContent;
        private String upgradeUrl;
        private TextView tvUpgrade;
        private LinearLayout llUpgradeContainer;
        private LinearLayout llUpgradingContainer;
        private ProgressBar progressBar;
        private UpgradeDialog dialog;

        public Builder(Context mContext) {
            this.mContext = mContext;
        }

        /**
         * 设置是否能够取消
         *
         * @param bool
         * @return
         */
        public Builder setCancel(boolean bool) {
            this.cancel = bool;
            return this;
        }

        /**
         * 设置app版本信息
         *
         * @param versionName
         * @return
         */
        public Builder setAppVersionName(String versionName) {
            this.versionName = versionName;
            return this;
        }

        /**
         * 设置app版本信息
         *
         * @param versionCode
         * @return
         */
        public Builder setAppVersionCode(int versionCode) {
            this.versionCode = versionCode;
            return this;
        }

        /**
         * 设置app更新内容
         *
         * @param upgradeContent
         * @return
         */
        public Builder setAppUpgradeContent(String upgradeContent) {
            this.upgradeContent = upgradeContent;
            return this;
        }

        /**
         * 设置app更新路径
         *
         * @param upgradeUrl
         * @return
         */
        public Builder setAppUpgradeUrl(String upgradeUrl) {
            this.upgradeUrl = upgradeUrl;
            return this;
        }

        /**
         * 设置显示正在下载
         */
        public void showUpgrading() {
            llUpgradeContainer.setVisibility(View.GONE);
            llUpgradingContainer.setVisibility(View.VISIBLE);
        }

        /**
         * 设置显示下载按钮
         */
        public void showUpgrade(String showText) {
            llUpgradeContainer.setVisibility(View.VISIBLE);
            llUpgradingContainer.setVisibility(View.GONE);
            if (TextUtil.isEmpty(showText)) {
                tvUpgrade.setText("立即更新");
            } else {
                tvUpgrade.setText(showText);
            }
        }

        /**
         * 创建
         *
         * @return
         */
        public UpgradeDialog create() {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            dialog = new UpgradeDialog(mContext, R.style.dialog_normal);
            View layout = inflater.inflate(R.layout.dialog_upgrade, null);
            dialog.addContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            dialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim);

            TextView tvVersionName = layout.findViewById(R.id.tvVersionName);
            TextView tvContent = layout.findViewById(R.id.tvContent);
            tvUpgrade = layout.findViewById(R.id.tvUpgrade);
            llUpgradeContainer = layout.findViewById(R.id.llUpgradeContainer);
            llUpgradingContainer = layout.findViewById(R.id.llUpgradingContainer);
            progressBar = layout.findViewById(R.id.progressBar);

            tvVersionName.setText(String.format("检测到%s", versionName));
            tvContent.setText(TextUtil.isEmptyConvert(upgradeContent));
            tvUpgrade.setOnClickListener(v -> {
                HttpUrl parsed = HttpUrl.parse(upgradeUrl);
                if (parsed == null) {
                    showUpgrade("重试");
                } else {
                    // 校验权限
                    try {
                        goToDownload();
                    } catch (Exception e) {
                        showUpgrade("重试");
                    }
                }
            });
            dialog.setContentView(layout);
            if (!cancel) {
                dialog.setCancelable(false);
            } else {
                dialog.setCancelable(true);
            }
            return dialog;
        }

        /**
         * 开始下载
         */
        private void goToDownload() {
            long thisTime = System.currentTimeMillis();
            // 判断文件是否存在
            String realFileName = "zsxqh_" + versionCode + ".apk";
            String tempFileName = "temp_zsxqh_" + versionCode + ".apk";
            boolean exist = FileUtils.checkFileExist(mContext, realFileName);
            if (exist) {
                //先下载临时文件
                String tag = "temp" + thisTime;
                downloadTempFile(tag, tempFileName, realFileName);
            } else {
                //开始下载真实文件
                String tag = "real" + thisTime;
                downloadFile(tag, realFileName);
            }
        }

        /**
         * 下载文件
         */
        private void downloadFile(String tag, String realFileName) {
            String savePath = mContext.getFilesDir().getAbsolutePath();
            if (TextUtil.isEmpty(upgradeUrl)) {
                ToastUtils.getInstance().toast("下载失败！！");
                return;
            }
            OkDownload.getInstance().setFolder(savePath);
            GetRequest<File> request = OkGo.get(upgradeUrl);
            OkDownload.request(tag, request).restart();
            OkDownload.request(tag, request)
                    .fileName(realFileName)
                    .save()
                    .register(new DownloadListener(tag) {
                        @Override
                        public void onStart(Progress progress) {
                            // 显示下载进度条
                            showUpgrading();
                        }

                        @Override
                        public void onProgress(Progress progress) {
                            progressBar.setProgress((int) (progress.fraction * 100));
                        }

                        @Override
                        public void onError(Progress progress) {
                            L.d("下载失败，exception:" + progress.exception.getMessage());
                            showUpgrade("重试");
                        }

                        @Override
                        public void onFinish(File file, Progress progress) {
                            if (file.exists()) {
                                ToastUtils.getInstance().toast("下载完成");
                                dialog.dismiss();
                                // 安装文件
                                FileUtils.install(mContext, file);
                            } else {
                                showUpgrade("重试");
                            }
                        }

                        @Override
                        public void onRemove(Progress progress) {

                        }
                    })
                    .start();
        }

        /**
         * 下载临时文件->删除旧的->重命名为新的
         */
        private void downloadTempFile(String tag, String tempFileName, String realFileName) {
            String savePath = mContext.getFilesDir().getAbsolutePath();
            OkDownload.getInstance().setFolder(savePath);
            if (TextUtil.isEmpty(upgradeUrl)) {
                ToastUtils.getInstance().toast("下载失败！！");
                return;
            }
            GetRequest<File> request = OkGo.get(upgradeUrl);
            OkDownload.request(tag, request).restart();
            OkDownload.request(tag, request)
                    .fileName(tempFileName)
                    .save()
                    .register(new DownloadListener(tag) {
                        @Override
                        public void onStart(Progress progress) {
                            // 显示下载进度条
                            showUpgrading();
                        }

                        @Override
                        public void onProgress(Progress progress) {
                            progressBar.setProgress((int) (progress.fraction * 100));
                        }

                        @Override
                        public void onError(Progress progress) {
                            L.d("下载失败，exception:" + progress.exception.getMessage());
                            showUpgrade("重试");
                        }

                        @Override
                        public void onFinish(File file, Progress progress) {
                            if (file.exists()) {
                                boolean deleteFile = FileUtils.deleteFile(savePath + "/" + realFileName);
                                if (deleteFile) {
                                    boolean renameState = FileUtils.renameFile(savePath, tempFileName, realFileName);
                                    if (renameState) {
                                        ToastUtils.getInstance().toast("下载完成");
                                        showUpgrade("下载完成");
                                        new Thread(() -> {
                                            try {
                                                Thread.sleep(1000);
                                                dialog.dismiss();
                                                // 安装文件
                                                FileUtils.install(mContext, file);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                        }).start();
                                    } else {
                                        showUpgrade("重试");
                                    }
                                } else {
                                    showUpgrade("重试");
                                }
                            } else {
                                showUpgrade("重试");
                            }
                        }

                        @Override
                        public void onRemove(Progress progress) {

                        }
                    })
                    .start();
        }
    }
}
